package com.liwang.lanouhn.nvshengo.fragments;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.liwang.lanouhn.nvshengo.Info.CosmeticInfo;
import com.liwang.lanouhn.nvshengo.Info.FeatureInfo;
import com.liwang.lanouhn.nvshengo.Info.Info;
import com.liwang.lanouhn.nvshengo.Info.NewFeatureInfo;
import com.liwang.lanouhn.nvshengo.Info.TutorialInfo;
import com.liwang.lanouhn.nvshengo.R;
import com.liwang.lanouhn.nvshengo.activities.FeatureDetailsActivity;
import com.liwang.lanouhn.nvshengo.adapter.FragmentCosmeticAdapter;
import com.squareup.picasso.Picasso;
import com.stx.xhb.xbanner.XBanner;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jp.wasabeef.recyclerview.adapters.SlideInLeftAnimationAdapter;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by lanouhn on 2016/9/29.
 */
public class CosmeticFragment extends Fragment implements XBanner.XBannerAdapter, View.OnClickListener {
    private XBanner xBanner;
    private String url = "http://api.meiyaapp.com/v1/slides?platform=2&place=1&channel=pp_" +
            "assistant&os=android&version=3.7.0.869&network=wifi&timestamp=1475137238&signature" +
            "=6610A2267FA2DDDD980DA39FEFCDAAFB";
    private List<String> imgesUrl;
    private FragmentCosmeticAdapter cosmeticAdapter;
    private TextView tv_makeup;
    private TextView tv_special;
    private XRecyclerView xRecyclerview;

    private CosmeticInfo cosmeticInfo = new CosmeticInfo();
    private List<String> titles;
    private List<String> urls;
    private List<Integer> likes;

    private List<Map<Integer, Object>> totalMap = new ArrayList<>();


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_cosmetic, null);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView(getView());
        initData();
        initEvent();
        getDataFromWeb();

    }


    private void initView(View view) {
        xRecyclerview = (XRecyclerView) view.findViewById(R.id.xRecyclerview);
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        xRecyclerview.setLayoutManager(manager);
        xRecyclerview.setOnClickListener(this);
        View view1 = LayoutInflater.from(getActivity()).inflate(R.layout.fragemnt_cosmeticup, null);
        xBanner = (XBanner) view1.findViewById(R.id.xBanner);
        TextView makeup = (TextView) view1.findViewById(R.id.makeup);
        TextView special = (TextView) view1.findViewById(R.id.special);
        tv_makeup = (TextView) view.findViewById(R.id.tv_makeup);
        tv_special = (TextView) view.findViewById(R.id.tv_special);
        xRecyclerview.addHeaderView(view1);
    }

    private void getDataFromWeb() {
        final String rurl = "http://api.meiyaapp.com/v2/feeds/digest-offset?comment_overview=3&show_good_topic=0&feed&feed_type=Post,Tutorial,Link,Feature,LiveRoom,Vote,TutoriaFeed&per_page=30&offset=0&show_vote=1&os=android&version=3.7.0.869&network=wifi&timestamp=1475888355&signature=9B222A28C3CA120FE5A0ADCFEFF5B08C";
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();
                final Request request = new Request.Builder().url(rurl).build();
                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        handler.sendEmptyMessage(0);
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string();
                        String finalResult = Html.fromHtml(result).toString();
                        try {
                            JSONObject object = new JSONObject(finalResult);
                            JSONArray array = object.getJSONArray("data");
                            for (int i = 0; i < array.length(); i++) {
                                JSONObject jsonObject = array.getJSONObject(i);
                                String feedable_type = jsonObject.getString("feedable_type");
                                if (feedable_type.equals("Tutorial")) {
                                    TutorialInfo tutorialInfo = new TutorialInfo();
                                    JSONObject model = jsonObject.getJSONObject("model");
                                    JSONArray images = jsonObject.getJSONArray("images");
                                    JSONObject user = model.getJSONObject("user");
                                    JSONArray video = model.getJSONArray("videos");
                                    tutorialInfo.setTimestamp(object.getLong("timestamp"));
                                    tutorialInfo.setId(jsonObject.getInt("id"));
                                    tutorialInfo.setFeedable_type(jsonObject.getString("feedable_type"));
                                    tutorialInfo.setTitle(jsonObject.getString("title"));
                                    tutorialInfo.setView_count(model.getInt("view_count"));
                                    tutorialInfo.setComment_count(model.getInt("comment_count"));
                                    tutorialInfo.setLike_count(model.getInt("like_count"));
                                    tutorialInfo.setUsername(user.getString("username"));
                                    tutorialInfo.setAvatar_url(user.getString("avatar_url"));
                                    tutorialInfo.setUrl(images.getJSONObject(0).getString("url"));
                                    tutorialInfo.setVideo_url(video.getJSONObject(0).getString("url"));
                                    Map<Integer, Object> map = new HashMap<Integer, Object>();
                                    map.put(0, tutorialInfo);
                                    totalMap.add(map);
                                } else if (feedable_type.equals("Feature")) {

                                    NewFeatureInfo newFeatureInfo = new NewFeatureInfo();
                                    JSONObject model = jsonObject.getJSONObject("model");
                                    JSONArray overviews = model.getJSONArray("overviews");
                                    if (overviews.length() == 0) {
                                        JSONArray images = jsonObject.getJSONArray("images");
                                        newFeatureInfo.setUrl(images.getJSONObject(0).getString("url"));
                                        newFeatureInfo.setNexturl(model.getString("url"));
                                        newFeatureInfo.setLike_count(model.getInt("like_count"));
                                        newFeatureInfo.setTitle(model.getString("title"));
                                        newFeatureInfo.setFeedable_type(jsonObject.getString("feedable_type"));
                                        Map<Integer, Object> map = new HashMap<Integer, Object>();
                                        map.put(1, newFeatureInfo);
                                        totalMap.add(map);
                                    } else {
                                        FeatureInfo featureInfo = new FeatureInfo();
                                        JSONObject models = jsonObject.getJSONObject("model");
                                        featureInfo.setTitle(models.getString("title"));
                                        featureInfo.setUrl(models.optString("url"));
                                        featureInfo.setFeedable_type(jsonObject.getString("feedable_type"));
                                        JSONArray jsonArray = models.getJSONArray("overviews");
                                        featureInfo.setLike_count(models.getInt("like_count"));
                                        List<FeatureInfo.OverViewsBean> overViewsBeanList = new ArrayList<FeatureInfo.OverViewsBean>();

                                        for (int a = 0; a < jsonArray.length(); a++) {
                                            JSONObject jsonObject1 = jsonArray.getJSONObject(a);
                                            FeatureInfo.OverViewsBean overViewsBean = new FeatureInfo.OverViewsBean();
                                            overViewsBean.setId(jsonObject1.getInt("id"));
                                            overViewsBean.setFeature_id(jsonObject1.getInt("feature_id"));
                                            overViewsBean.setTitle(jsonObject1.getString("title"));
                                            overViewsBean.setCover_url(jsonObject1.getString("cover_url"));
                                            overViewsBean.setPriority(jsonObject1.getInt("priority"));
                                            overViewsBean.setAnchor_id(jsonObject1.getInt("anchor_id"));
                                            overViewsBeanList.add(overViewsBean);
                                        }
                                        featureInfo.setOverviews(overViewsBeanList);
                                        Map<Integer, Object> map = new HashMap<Integer, Object>();
                                        map.put(2, featureInfo);
                                        totalMap.add(map);
                                    }


                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


//                        Gson gson =new Gson();
//                        cosmeticInfo =gson.fromJson(result,CosmeticInfo.class);
                        if (totalMap.size() > 0) {
                            handler.sendEmptyMessage(1);
                        } else {
                            handler.sendEmptyMessage(0);
                        }

                    }
                });
            }
        }).start();


    }


    private void initData() {
        imgesUrl = new ArrayList<>();
        imgesUrl.add("http://meiya.qiniudn.com/2016/10/19/o_1avdbfqib1br25mb15gv12bjkt7h29702.jpg");
        imgesUrl.add("http://meiya.qiniudn.com/2016/10/18/o_1avbk6k04bgm1b9m1lag18t1upch53921.JPG");
        imgesUrl.add("http://meiya.qiniudn.com/2016/10/14/o_1av17nelv1hlq1g481iavtgg1icr1522389.png");
        xBanner.setData(imgesUrl);
        xBanner.setmAdapter(this);
        titles = new ArrayList<>();
        titles.add("韩妆博主都爱用的染唇液TOP20 大公开");
        titles.add("怪粉底液？是你没get到正确的上妆手法");
        titles.add("VANT36.5不沾杯唇彩笔[免费试用]啦~");
        urls = new ArrayList<>();
        urls.add("http://st-tx.meiyaapp.com/feature/feature_710.html?1476843009");
        urls.add("http://st-tx.meiyaapp.com/feature/feature_712.html?1476785498");
        urls.add("http://act.meiyaapp.com/gw.php?name=trade/20161014&id=13");
        likes = new ArrayList<>();
        likes.add(169);
        likes.add(32);
        likes.add(69);

    }

    private void initEvent() {
        xBanner.setOnItemClickListener(new XBanner.OnItemClickListener() {
            @Override
            public void onItemClick(XBanner banner, int position) {

                Info info = new Info();
                info.setTitle(titles.get(position));
                info.setLike_count(likes.get(position));
                info.setUrl(urls.get(position));
                Intent intent = new Intent(getActivity(), FeatureDetailsActivity.class);
                intent.putExtra("featureInfo", info);
                startActivity(intent);


            }
        });
    }

    @Override
    public void loadBanner(XBanner banner, View view, int position) {

        Picasso.with(getActivity()).load(imgesUrl.get(position)).fit().config(Bitmap.Config.RGB_565).into((ImageView) view);

    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    Toast.makeText(getActivity(), "网络请求失败!", Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    cosmeticAdapter = new FragmentCosmeticAdapter(getActivity(), totalMap);
                    xRecyclerview.setAdapter(new SlideInLeftAnimationAdapter(cosmeticAdapter));
                    xRecyclerview.setLoadingListener(new XRecyclerView.LoadingListener() {
                        @Override
                        public void onRefresh() {
                            xRecyclerview.refreshComplete();
                        }

                        @Override
                        public void onLoadMore() {

                        }
                    });
                    break;

                case 2:
                    //最后一页
                    Toast.makeText(getActivity(), " 已经是最后一页啦 !", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @Override
    public void onClick(View view) {

    }
}
